package com.financing.service.user;
import java.util.Date;
import java.util.List;

import com.financing.model.user.Token;
import com.financing.model.user.User;
import com.financing.service.BaseService;
import com.financing.util.DateUtil;
import com.financing.util.MD5Util;
import com.financing.util.Str;
import com.jfinal.kit.Ret;

public class TokenService extends BaseService<User>{

	/**
	 * 根据token判断登陆
	 */
	public Ret check(String tk) {
		Token al = this.findByToken(tk);
		// 48小时后过期 
		if(al!=null) {
			if(Long.valueOf(DateUtil.getTimeStamp())-al.getUpdateTime().getTime()<=172800000){
				return Ret.ok("mobile",Str.hideMobile(al.getMobile()));
			} else {
				return Ret.fail("msg", "TOKEN超时！");
			} 
		}else{
			return Ret.fail("msg", "TOKEN校验失败！");
		}
	}	
	
	/**
	 * 刷新token
	 */
	public String refresh(User u, String type) {
		Token app = this.findByUser(u.getId(),type);
		String token = MD5Util.encrypt(u.getMobile()+DateUtil.getTimeStamp());
		Date now = new Date();
		if(app != null) {  
			app.setToken(token);
			app.setType(type);
			app.setUserId(u.getId());
			app.setUpdateTime(now);
			app.update(); 
		} else {
			app = new Token();
			app.setToken(token);
			app.setMobile(u.getMobile());
			app.setType(type);
			app.setUserId(u.getId());
			app.setCreateTime(now);
			app.setUpdateTime(now);
			app.save();
		}
		return token;
	}	

	/**
	 * 根据TOKEN查找记录
	 */
	public Token findByToken(String token) {
		return Token.me.findFirst("select * from token where token=?", token);
	}
	
	/**
	 * 根据手机号删除设备号登陆记录
	 */
	public void removeByMobile(String mobile, String type) {
		String where = Str.eq("backend", type) ? " and type='backend' " : " and type<>'backend' ";
		List<Token> list = Token.me.find("select * from token where mobile=?"+where, mobile);
		for(Token item : list){
			item.setToken("").update();
		}
	}

	/**
	 * 根据手机号返回token
	 */
	public Token findByUser(int userId, String type) {
		String where = Str.eq("backend", type) ? " and type='backend' " : " and type<>'backend' ";
		return Token.me.findFirst("select * from token where user_id=? "+where, userId);
	}

	/**
	 * 根据token获取用户
	 */
	public User findUserByToken(String token) { 
		return User.me.findFirst("select u.* from user u left join token al on u.id = al.user_id where al.token=?",token);
	}
}
